<template>
	<view class="container">
		<view class="headimg">
			<image :src="avatarImg" mode=""></image>
		</view>
		<button @click="onChooseHeader">更换头像</button>
	</view>
</template>

<script>
	import {
		uploadAvatar
	} from '@/api/account/account.js';
	import config from '@/config'
	import {
		getToken,
		getUserAdmin,
		setUserAdmin
	} from '@/utils/auth'
	import cryptoUtils from "@/utils/cryptoUtils"; //引入静态变量
	import {
		toast,
	} from '@/utils/common'
	import {
		updateAvatar
	} from '@/api/account/account.js'

	const baseUrl = config.baseUrl
	const imgUrl = config.imgUrl
	export default {
		onLoad(option) {
			this.avatarImg = option.avatarImg
		},
		data() {
			return {
				avatarImg: "", //头像地址
			}
		},
		methods: {
			// 选择相册或者拍摄,并上传
			onChooseHeader() {
				let _this = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册和拍照
					success: function(res) {
						const tempFilePaths = res.tempFilePaths;
						uni.uploadFile({
							url: baseUrl + "/uploadController/open/ossUploadCustomizeFileName",
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								'folderName': 'avatar'
							},
							header: {
								"Authorization": getToken()
							},
							success: (uploadFileRes) => {
								let res = JSON.parse(uploadFileRes.data);
								res.data = cryptoUtils.decrypt(res.data)
								if (res.code == 200) {
									if (res.data[0]) {
										_this.avatarImg = imgUrl + res.data[0]
										updateAvatar(res.data[0]).then((res) => {
											if (res.code == 200) {
												// console.log(res.data, "修改头像")
												setUserAdmin(res.data)
												toast("修改成功");
												setTimeout(function() {
													uni.navigateTo({
														url: "/pages/Account/Account"
													});
												}, 1000)
											}
										})
									}
								} else {
									toast(res.msg)
								}

							}
						});
					}
				});
			},
		}
	}
</script>

<style scoped lang="less">
	.container {
		padding-top: 150rpx;
		.headimg{
			width: 680rpx;
			height: 640rpx;
			margin: 0 40rpx;
			border-radius: 17rpx;
			image{
				width: 680rpx;
				height: 640rpx;
				border-radius: 17rpx;
			}
		}
		button {
			width: 680rpx;
			height: 98rpx;
			line-height:105rpx;
			margin-top: 480rpx;
			background: linear-gradient(270deg, #4463FF 0%, #3ADDEB 100%);
			box-shadow: 3rpx 3rpx 5rpx 0rpx rgba(0, 0, 0, 0.15);
			border-radius: 16rpx;
			font-size: 28rpx;
			font-family: "font";
			font-weight: 800;
			color: #ffffff;
		}
	}
</style>